import React, { useEffect, useState } from "react";
import { Button, Table, message, Popconfirm, DatePicker, Tag } from "antd";
import {
  listPurchaseOrders,
  createPurchaseOrder,
  updatePurchaseOrder,
  deletePurchaseOrder,
  listProducts,
  listUsers,
  listSuppliers,
  listWarehouseProducts,
} from "../../api/ckgl";
import PurchaseOrderModal from "./componets/PurchaseOrderModal";
import { PurchaseOrder } from "../../api/type/ckgl";

const ListPurchaseOrders = () => {
  const [purchaseOrderList, setPurchaseOrderList] = useState<any[]>([]);
  const [totalPurchaseOrders, setTotalPurchaseOrders] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20);
  const [isPurchaseOrderModalVisible, setIsPurchaseOrderModalVisible] =
    useState(false);
  const [currentPurchaseOrder, setCurrentPurchaseOrder] = useState<any>(null);
  const [productList, setProductList] = useState<any[]>([]);
  const [list, setList] = useState<any[]>([]);
  const [warehouseProductList, setWarehouseProductList] = useState<any[]>([]);

  // //  @int32
  // order_id: number;
  // //  @int32
  // product_id: number;
  // //  @int32
  // supplier_id: number;
  // //  @int32
  // quantity: number;
  // // 1-待交付,2-运输中,3-已送达 @int32
  // delivery_progress: number;
  // // 1-待付款,2-已付款 @int32
  // payment_status: number;
  const columns = [
    {
      title: "订单ID",
      dataIndex: "id",
      key: "id",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "产品",
      dataIndex: "product_name",
      key: "product_name",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "供应商",
      dataIndex: "supplier_name",
      key: "supplier_name",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "数量",
      dataIndex: "quantity",
      key: "quantity",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "交付进度",
      dataIndex: "delivery_progress",
      key: "delivery_progress",
      render: (progress: number) => {
        let color, text;
        switch (progress) {
          case 1:
            color = "orange";
            text = "待交付";
            break;
          case 2:
            color = "blue";
            text = "运输中";
            break;
          case 3:
            color = "green";
            text = "已送达";
            break;
          default:
            color = "gray";
            text = "";
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: "付款状态",
      dataIndex: "payment_status",
      key: "payment_status",
      render: (status: number) => {
        const color = status === 1 ? "red" : "green";
        const text = status === 1 ? "待付款" : "已付款";
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: "操作",
      dataIndex: "id",
      key: "id",
      render: (_: any, record: any) => (
        <>
          <>
            <Button type="link" onClick={() => handleEditPurchaseOrder(record)}>
              编辑
            </Button>
            <Popconfirm
              okText="确定"
              cancelText="取消"
              title="确定删除采购订单"
              onConfirm={() => handleDeletePurchaseOrder(record)}
            >
              <Button type="link" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        </>
      ),
    },
  ];

  const handleDeletePurchaseOrder = (record: any) => {
    deletePurchaseOrder({
      purchase_order_id: record.id,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      message.success(`采购订单 "${record.product_name}" 删除成功`);
      // 更新当前页
      reset(currentPage);
    });
  };

  const handleEditPurchaseOrder = (record: any) => {
    setCurrentPurchaseOrder(record);
    setIsPurchaseOrderModalVisible(true);
  };

  const getListPurchaseOrders = (page: number) => {
    // 调用 listPurchaseOrders API，并处理响应
    listPurchaseOrders({
      page,
      size: pageSize,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { purchase_orders, total } = res.data;
      setPurchaseOrderList(purchase_orders);
      setTotalPurchaseOrders(total);
    });
  };

  const reset = (page: number) => {
    getListPurchaseOrders(page);
  };

  const handlePurchaseOrderModalOk = async (values: any) => {
    console.log("values", values);
    // 根据情况调用 createPurchaseOrder 或 updatePurchaseOrder API，并处理响应
    if (currentPurchaseOrder) {
      // 更新
      let msg = "更新成功";
      // message UpdatePurchaseOrderReq {
      //   int32 purchase_order_id = 1;
      //   int32 product_id = 2;
      //   int32 supplier_id = 3;
      //   int32 quantity = 4;
      //   int32 delivery_progress = 5; // 1-待交付,2-运输中,3-已送达 （更新的注意事项，已经是已送达状态的不能在更新该状态）
      //   int32 payment_status = 6; // 1-待付款,2-已付款 （下面同样）
      // }
      await updatePurchaseOrder({
        purchase_order_id: currentPurchaseOrder?.id || "",
        ...values,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        message.success(msg);
      });
    } else {
      // 添加
      let msg = "添加成功";
      await createPurchaseOrder({
        ...values,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        message.success(msg);
      });
    }
    reset(currentPage);
    setIsPurchaseOrderModalVisible(false);
  };

  useEffect(() => {
    getListPurchaseOrders(currentPage);
  }, [currentPage]);

  useEffect(() => {
    // getListProducts();
    getListWarehouseProducts();
    getListSuppliers();
  }, []);

  const getListSuppliers = () => {
    // 调用 listSuppliers API，并处理响应
    listSuppliers({
      page: 1,
      size: 300,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { suppliers, total } = res.data;
      setList(suppliers);
    });
  };

  // const getListProducts = () => {
  //   // 调用 listProducts API，并处理响应
  //   listProducts({
  //     page: 1,
  //     size: 300,
  //   }).then((res: any) => {
  //     if (res?.code !== 0) {
  //       message.error(res.msg);
  //       return;
  //     }
  //     const { products, total } = res.data;
  //     setProductList(products);
  //   });
  // };

  const getListWarehouseProducts = () => {
    // 调用 listWarehouseProducts API，并处理响应
    listWarehouseProducts({
      page: 1,
      size: 300,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { warehouse_products, total } = res.data;
      setWarehouseProductList(warehouse_products);
    });
  };

  return (
    <div>
      <Button
        style={{ marginTop: "7px", marginLeft: "10px", float: "right" }}
        onClick={() => {
          setIsPurchaseOrderModalVisible(true);
          setCurrentPurchaseOrder(null);
        }}
        size="large"
        type="primary"
      >
        添加采购订单
      </Button>
      <Table
        dataSource={purchaseOrderList}
        columns={columns}
        rowKey="id"
        pagination={{
          pageSize,
          defaultCurrent: 1,
          onChange: setCurrentPage,
          total: totalPurchaseOrders,
        }}
      />
      <PurchaseOrderModal
        users={list}
        warehouseProductList={warehouseProductList}
        // productList={productList}
        title={currentPurchaseOrder ? "编辑采购订单" : "添加采购订单"}
        visible={isPurchaseOrderModalVisible}
        onCancel={() => setIsPurchaseOrderModalVisible(false)}
        onOk={handlePurchaseOrderModalOk}
        defaultValue={currentPurchaseOrder || {}}
      />
    </div>
  );
};

export default ListPurchaseOrders;
